
package com.zjff.myshop.admin.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.hutool.core.util.StrUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zjff.myshop.admin.pojo.form.BatchIdsForm;
import com.zjff.myshop.admin.pojo.form.ResetPasswordForm;
import com.zjff.myshop.admin.pojo.form.UserQueryPageForm;
import com.zjff.myshop.front.pojo.form.UserUpdateForm;
import com.zjff.myshop.front.pojo.vo.UserVO;
import com.zjff.myshop.entity.User;
import com.zjff.myshop.exception.BusinessException;

import com.zjff.myshop.admin.service.UserService;
import com.zjff.myshop.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;

@CrossOrigin
@RestController
@Api(value = "v1", tags = "86.后台管理系统-注册用户模块")
@SaCheckRole("admin")
@RequestMapping("/admin/v1/user")
public class AdminUserController {
    private static final Logger logger = LoggerFactory.getLogger(AdminUserController.class);
    @Resource
    private UserService userService;
    // 注册用户，后台管理没有新增功能

    /**
     * 删除（单个）
     */
    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "删除单个用户", notes = "删除单个注册用户")
    @DeleteMapping(value = "/{id}")
    public Result deleteById(@PathVariable Integer id) {
        logger.info("删除用户：" + id);
        if (userService.deleteById(id)) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    /**
     * 删除（批量）
     */
    @ApiOperationSupport(order = 11)
    @ApiOperation(value = "批量删除", notes = "批量删除注册用户")
    @ApiImplicitParam(name = "form", value = "批量删除参数", dataType = "BatchIdsForm", required = true)
    @DeleteMapping(value = "/batch")
    public Result deleteBatch(@RequestBody @Valid BatchIdsForm form) {
        if (form == null || form.getIds().length < 1) {
            throw new BusinessException("数据不存在！");
        }

        if (userService.deleteBatchByIds(form.getIds())) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    /**
     * 更改用户
     */
    @ApiOperationSupport(order = 20)
    @ApiOperation(value = "更改用户信息", notes = "用户id不能未空，也可以更改密码")
    @ApiImplicitParam(name = "form", value = "更改用户信息参数", dataType = "UserUpdateForm", required = true)
    @PostMapping("/update")
    public Result update(@RequestBody @Valid UserUpdateForm form) {
        int userId = form.getId();
        User user = userService.selectByPrimaryKey(userId);
        if (user == null) {
            throw new BusinessException("用户数据不存在！");
        }

        //若密码不为空字符，则表明用户打算更改密码
        String password = form.getPassword();
        if (StrUtil.isNotBlank(password)) {
            String passwordMd5 = MD5Util.md5Encode(password + user.getSalt(), "UTF-8");
            form.setPassword(passwordMd5);
        } else {
            form.setPassword(null);
        }

        User userForUpdate = new User();
        BeanUtils.copyProperties(form, userForUpdate);

        if (userService.update(userForUpdate)) {//返回成功
            return Result.ok();
        } else { //返回失败
            return Result.error();
        }
    }

    /**
     * 重置用户密码
     */
    @ApiOperationSupport(order = 25)
    @ApiOperation(value = "重置用户密码息", notes = "用户id不能未空，重置用户密码码")
    @ApiImplicitParam(name = "form", value = "重置密码参数", dataType = "ResetPasswordForm", required = true)
    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody @Valid ResetPasswordForm form) {
        int userId = form.getId();
        User user = userService.selectByPrimaryKey(userId);
        if (user == null) {
            throw new BusinessException("用户数据不存在！");
        }

        //若密码不为空字符，则表明用户打算更改密码
        String password = form.getPassword();
        if (StrUtil.isNotBlank(password)) {
            String passwordMd5 = MD5Util.md5Encode(password + user.getSalt(), "UTF-8");
            form.setPassword(passwordMd5);
        } else {
            throw new BusinessException("数据不存在！");
        }

        User userForUpdate = new User();
        BeanUtils.copyProperties(form, userForUpdate);

        if (userService.update(userForUpdate)) {//返回成功
            return Result.ok();
        } else { //返回失败
            return Result.error();
        }
    }

    /**
     * 查询用户详情
     */
    @ApiOperationSupport(order = 30)
    @ApiOperation(value = "查询用户详情", notes = "查询注册用户的详情信息")
    @GetMapping("/{id}")
    public Result<UserVO> getById(@PathVariable Integer id) {
        User user = userService.selectByPrimaryKey(id);
        if (user == null) {
            throw new BusinessException("用户数据不存在！");
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return Result.ok(userVO);
    }

    /**
     * 查询分页列表
     */
    @ApiOperationSupport(order = 31)
    @ApiOperation(value = "查询注册用户分页", notes = "查询注册用户分页")
    @ApiImplicitParam(name = "form", value = "参数", dataType = "UserQueryPageForm", required = true)
    @PostMapping(value = "/queryPage")
    public Result<PageList<UserVO>> queryPage(@Valid @RequestBody UserQueryPageForm form) {
        //page参数有 ：page limit keyword  orderBy
        Map<String, Object> map = BeanUtils.beanToMap(form);
        PageQuery pageQuery = new PageQuery(map);
        return Result.ok(userService.selectPage(pageQuery));
    }
}